﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.DynamicData;
using System.Web.UI;
using FlexiCommerce.Collections;
using FlexiCommerce.Components;
using FlexiCommerce.Web.UI;
using Image = System.Web.UI.WebControls.Image;
using System.Web.UI.WebControls;

namespace FlexiCommerce.Web.DynamicData.FieldTemplates
{
    public partial class Images_Edit : FieldTemplateUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected string GetImageUrl(string id)
        {
            return Page.ResolveUrl("~/flexicommerce/image.ashx?id=" + id + "&size=tiny");
        }
        protected void ImageSelected(object sender, ItemEventArgs e)
        {
            ViewStateImages.Add(e.AffectedItem as Components.Image);
        }
        public override void DataBind()
        {

            List<Components.Image> images = new List<Components.Image>();
            if (Host.Mode == DataBoundControlMode.Edit)
            {
                this.DataObjectID = ((PersistenceItem)Row).ID;
                foreach (Components.Image image in base.FieldValue as IList<Components.Image>)
                {
                    images.Add(image);
                }
            }
            ViewStateImages = images;
            base.DataBind();
        }
        public override Control DataControl
        {
            get
            {
                return GridViewImages;
            }
        }
        private Type DataObjectType
        {
            get { return ViewState["DataObjectType"] == null ? typeof(PersistenceItem) : (Type)ViewState["DataObjectType"]; }
            set { ViewState["DataObjectType"] = value; }
        }
        private int DataObjectID
        {
            get { return ViewState["DataObjectID"] == null ? 0 : (int)ViewState["DataObjectID"]; }
            set { ViewState["DataObjectID"] = value; }
        }
        protected override void ExtractValues(System.Collections.Specialized.IOrderedDictionary dictionary)
        {
            IList<Components.Image> images = new List<Components.Image>();
            foreach (Components.Image image in ViewStateImages)
            {
                images.Add(FlexiCommerce.Context.Persister.Get<Components.Image>(image.ID));
            }
            dictionary[Column.Name] = images;
        }

        public List<Components.Image> ViewStateImages
        {
            get { return (List<Components.Image>)ViewState["ViewStateImages"]; }
            set { ViewState["ViewStateImages"] = value; }
        }
        protected override void OnPreRender(EventArgs e)
        {
            List<Components.Image> sorted = null;
            sorted = ViewStateImages;
            GridViewImages.DataSource = sorted;
            GridViewImages.DataBind();
            base.OnPreRender(e);
        }


    }
}